package handlers

import (
	"fmt"
	"net/http"
	"strings"
	
	"github.com/gin-gonic/gin"
	"keystone-auth-portal/services"
)

type AuthHandler struct {
	keystoneService *services.KeystoneService
	config          map[string]interface{}
}

func NewAuthHandler(keystoneService *services.KeystoneService, config map[string]interface{}) *AuthHandler {
	return &AuthHandler{
		keystoneService: keystoneService,
		config:          config,
	}
}

func (h *AuthHandler) LoginPage(c *gin.Context) {
	c.HTML(http.StatusOK, "login.html", gin.H{
		"title": "企业云资源申请系统",
		"users": h.getTestUsers(),
	})
}

func (h *AuthHandler) Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password") 
	domain := c.PostForm("domain")
	
	if username == "" || password == "" {
		c.HTML(http.StatusBadRequest, "login.html", gin.H{
			"error": "用户名和密码不能为空",
			"users": h.getTestUsers(),
		})
		return
	}
	
	// 使用Keystone验证用户，系统自动选择项目
	userContext, err := h.keystoneService.AuthenticateUser(username, password, domain, "")
	if err != nil {
		c.HTML(http.StatusUnauthorized, "login.html", gin.H{
			"error": "认证失败: " + err.Error(),
			"users": h.getTestUsers(),
		})
		return
	}
	
	// 保存用户会话到session (简化实现，生产环境建议使用Redis)
	c.SetCookie("user_session", userContext.Token, 3600*2, "/", "", false, true)
	c.SetCookie("username", userContext.Username, 3600*2, "/", "", false, false)
	c.SetCookie("user_roles", fmt.Sprintf("%v", userContext.Roles), 3600*2, "/", "", false, false)
	c.SetCookie("project_name", userContext.ProjectName, 3600*2, "/", "", false, false)
	
	// 根据用户角色重定向到不同页面
	redirectURL := h.getRedirectURL(userContext)
	c.Redirect(http.StatusFound, redirectURL)
}

func (h *AuthHandler) Logout(c *gin.Context) {
	// 清除所有会话cookies
	c.SetCookie("user_session", "", -1, "/", "", false, true)
	c.SetCookie("username", "", -1, "/", "", false, false)
	c.SetCookie("user_roles", "", -1, "/", "", false, false)
	c.SetCookie("project_name", "", -1, "/", "", false, false)
	
	c.Redirect(http.StatusFound, "/")
}

func (h *AuthHandler) getTestUsers() []map[string]interface{} {
	testAccounts := h.config["test_accounts"].(map[string]interface{})
	users := make([]map[string]interface{}, 0)
	
	for accountType, accountConfig := range testAccounts {
		accountData := accountConfig.(map[string]interface{})
		users = append(users, map[string]interface{}{
			"type":        accountType,
			"username":    accountData["username"],
			"password":    accountData["password"],
			"description": accountData["description"],
		})
	}
	
	return users
}

func (h *AuthHandler) getRedirectURL(userContext *services.UserContext) string {
	// 根据用户角色确定重定向页面
	for _, role := range userContext.Roles {
		switch role {
		case "project-manager":
			return "/dashboard/manager"
		case "team-leader":
			return "/dashboard/leader"
		case "developer":
			return "/dashboard/developer"
		case "resource-admin":
			return "/dashboard/admin"
		case "auditor":
			return "/dashboard/auditor"
		}
	}
	
	return "/dashboard/default"
}

func (h *AuthHandler) RequireAuth(c *gin.Context) {
	// 从cookie获取用户信息
	token, err := c.Cookie("user_session")
	if err != nil {
		c.Redirect(http.StatusFound, "/")
		c.Abort()
		return
	}
	
	username, err := c.Cookie("username")
	if err != nil {
		c.Redirect(http.StatusFound, "/")
		c.Abort()
		return
	}
	
	rolesStr, err := c.Cookie("user_roles")
	if err != nil {
		c.Redirect(http.StatusFound, "/")
		c.Abort()
		return
	}
	
	projectName, err := c.Cookie("project_name")
	if err != nil {
		c.Redirect(http.StatusFound, "/")
		c.Abort()
		return
	}
	
	// 解析角色字符串 "[role1 role2]" -> []string{"role1", "role2"}
	rolesStr = strings.Trim(rolesStr, "[]")
	var roles []string
	if rolesStr != "" {
		roles = strings.Fields(rolesStr)
	}
	
	// 构建用户上下文
	userContext := &services.UserContext{
		Username:    username,
		Token:       token,
		ProjectName: projectName,
		DomainName:  "company-cloud",
		Roles:       roles,
	}
	
	c.Set("user", userContext)
	c.Next()
}

func (h *AuthHandler) getUserRoles(username string) []string {
	// 根据配置文件中的测试账号返回角色
	testAccounts := h.config["test_accounts"].(map[string]interface{})
	
	for _, accountConfig := range testAccounts {
		accountData := accountConfig.(map[string]interface{})
		if accountData["username"].(string) == username {
			if expectedRoles, exists := accountData["expected_roles"]; exists {
				roles := expectedRoles.([]interface{})
				result := make([]string, len(roles))
				for i, role := range roles {
					result[i] = role.(string)
				}
				return result
			}
			if domainRoles, exists := accountData["domain_roles"]; exists {
				roles := domainRoles.([]interface{})
				result := make([]string, len(roles))
				for i, role := range roles {
					result[i] = role.(string)
				}
				return result
			}
		}
	}
	
	return []string{}
}

func (h *AuthHandler) RequireRole(requiredRoles ...string) gin.HandlerFunc {
	return func(c *gin.Context) {
		user, exists := c.Get("user")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "未登录",
			})
			c.Abort()
			return
		}
		
		userContext := user.(*services.UserContext)
		
		hasRole := false
		for _, userRole := range userContext.Roles {
			for _, requiredRole := range requiredRoles {
				if userRole == requiredRole {
					hasRole = true
					break
				}
			}
			if hasRole {
				break
			}
		}
		
		if !hasRole {
			c.JSON(http.StatusForbidden, gin.H{
				"error": "权限不足，需要以下角色之一: " + fmt.Sprintf("%v", requiredRoles),
			})
			c.Abort()
			return
		}
		
		c.Next()
	}
}